package com.example.sophia

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import android.util.Log


class ChatAdapter(private val chatMessages: MutableList<ChatMessage>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val view = if (viewType == 0) {
            inflater.inflate(R.layout.item_chat_left, parent, false)
        } else {
            inflater.inflate(R.layout.item_chat_right, parent, false)
        }

        if (viewType == 0) {
            return ChatRecViewHolder(view)
        }
        return ChatSendViewHolder(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val message = chatMessages[position]
        when(holder) {
            is ChatRecViewHolder -> holder.leftTextView.text = message.message
            is ChatSendViewHolder -> holder.rightTextView.text = message.message
        }
    }

    override fun getItemCount(): Int = chatMessages.size

    override fun getItemViewType(position: Int): Int =
        if (chatMessages[position].isSentByMe) 1 else 0

    class ChatRecViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val leftTextView: TextView = itemView.findViewById(R.id.leftTextMessage)
    }

    class ChatSendViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val rightTextView: TextView = itemView.findViewById(R.id.rightTextMessage)
    }
}